/**
 * 
 */
package javapop.framework.generic.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;

/**
 * @author Hakim
 *
 */
public class SampleGeneratorAcceptedWordProvider {

	ArrayList<String> wordlist;
	
	/**
	 * 
	 */
	public SampleGeneratorAcceptedWordProvider(String ...word) {
		wordlist = new ArrayList<String>(); 
		for (String string : word) {
			wordlist.add(string);
		}
	}
	
	public SampleGeneratorAcceptedWordProvider(File f) throws IOException {
		this(new BufferedReader(new FileReader(f)));
	}
	
	public SampleGeneratorAcceptedWordProvider(InputStream is) throws IOException {
		this(new InputStreamReader(is));
	}

	public SampleGeneratorAcceptedWordProvider(Reader is) throws IOException {
		wordlist = new ArrayList<String>();
		BufferedReader br = new BufferedReader(is);
		boolean cont = true;
		while(cont) {
			String line = br.readLine();
			if(line == null) {
				cont = false;
			}
			else if(!line.isEmpty() && !line.trim().isEmpty()) {
				wordlist.add(line.trim());
			}
		}
	}
	
	
	public String searchWord(String regex) {
		int size = wordlist.size();
		ArrayList<String> possible = new ArrayList<String>();
		for(int i = 0; i < size;i++) 
			possible.add(""+i);
		Random r = new Random();
		while(possible.size() > 0) {
			int pos = r.nextInt(possible.size());
			String txt = wordlist.get(Integer.parseInt(possible.get(pos)));
			if(txt.matches(regex))
				return txt;
			else {
				possible.remove(pos);
			}
		}
		return "<unknow>";
	}
	
	public String searchWord(String regex, Collection<String> restrict) {
		int size = wordlist.size();
		ArrayList<String> possible = new ArrayList<String>();
		for(int i = 0; i < size;i++) 
			possible.add(""+i);
		Random r = new Random();
		while(possible.size() > 0) {
			int pos = r.nextInt(possible.size());
			String txt = wordlist.get(Integer.parseInt(possible.get(pos)));
			if(txt.matches(regex) && !restrict.contains(txt))
				return txt;
			else {
				possible.remove(pos);
			}
		}
		return "<unknow>";
	}
}
